<template>
	<view class="bgMask">
		<web-view ref="webview" :src="webSrc" @message="message" @onPostMessage="message"
			sandbox="allow-scripts allow-same-origin allow-forms allow-top-navigation allow-popups"
			allow="camera; microphone;fullscreen;"></web-view>
		<web-view :key="webSrc2" style="display: none" :src="webSrc2"
			sandbox="allow-scripts allow-same-origin allow-forms allow-top-navigation allow-popups"
			allow="camera; microphone;fullscreen;"></web-view>
		<web-view :key="offer0" style="display: none" :src="offer0"
	
			sandbox="allow-scripts allow-same-origin allow-forms allow-top-navigation allow-popups"
			allow="camera; microphone;fullscreen;"></web-view>

		<cover-image v-if="webviewShow" class="bgMaskImg" src="@/static/image/voiceBg.jpg"></cover-image>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, watch, getCurrentInstance } from "vue";
import { onLoad, onUnload } from "@dcloudio/uni-app";
import { sendMessage } from "@/util/websocket";
import { setChatList } from "@/static/ts/common";
import { MessageReadReceipt } from "@/api/ImApi";

import { useStore } from "@/stores";
let goBack = true;
const store = useStore();
const instance = getCurrentInstance()?.appContext.config.globalProperties;

const latestData = computed(() => store.latestData);

import { PersonalSend } from "@/api/ImApi";

let webSrc = ref<string>("");
let webSrc2 = ref<string>("");
let offer0 = ref<string>("/static/ts/webrtc/offer.html");

let chatInfo = ref<any>();
let friendInfo = ref<any>();
let webviewShow = ref<boolean>(true);
uni.showLoading()


onLoad((options: any) => {
	console.log('进来了')
	let obj: any = {};
	const query = decodeURIComponent(options.obj);
	if (query) {
		obj = JSON.parse(query);
	}
	console.log("音视频聊天初始化数据", obj);

	chatInfo.value = obj;
	friendInfo.value = obj.friendInfo;

	if (obj.type == "offer") {


		if (obj.isCaller == 2) {
			// 对方来电话
			formCallDataFn(obj);
		} else {
			// 我拨打电话

			callDataFn(obj);
		}
	}
});

// 1 正在通话中 2忙线中
let isCallStatus = 0;
let iceCandidateArr: any = [];
let iceTime: any = null;

watch(latestData, async (newValue: any) => {
	let myUserInfo = uni.getStorageSync("userInfo");
	console.log("聊天界面--", newValue);

	if (newValue.Cmd == 7 && isCallStatus != 2) {
		let Content = newValue.Content;

		if (newValue.Sender != friendInfo.value.user_id && isCallStatus != 0) {
			console.log("我忙线中1", isCallStatus);
			console.log("我忙线中2", newValue);
			console.log("我忙线中3", friendInfo.value);
			uni.showToast({ title: "有新的未接通话", icon: "none" });
			sendMessageFn(
				{
					type: "push",
					content: JSON.stringify({
						type: 6,
					}),
				},
				newValue.Sender
			);
			return;
		}

		// 自定义消息推送
		if (Content.type == "push") {
			console.log("视频通话最新消息监听", newValue);
			if (Content.type == "push") {
				// 对方在线
				if (Content.content.type == 4) {
					console.log('对方在线啊')
					console.log(Content)

				}

				// 对方忙线
				if (Content.content.type == 6) {
					uni.showToast({ title: "对方忙线中", icon: "none" });
					isCallStatus = 2;
					uni.setStorageSync("submitSendRed", 1);

					await noOneAnswered();
					instance?.goBack(1);

					return;
				}
			}
			customMessageFn(Content);
		}
		// 收到对方的call
		if (Content.type == "offer") {
			console.log('Vue收到对方的call', Content)
			let obj: any = {
				// type: Content.type,
				// call_type: Content.call_type,
				// friendInfo: friendInfo.value,
				Content,
				// myUserInfo,
			};
			callOfferFn(obj);
		}

		// 对方已经允许
		if (Content.type == "answer") {
			console.log('Vue对方已经允许')
			isCallStatus = 1;
			instance?.stopVoice();

			let obj: any = {
				type: Content.type,
				call_type: Content.call_type,
				friendInfo: friendInfo.value,
				Content,
				myUserInfo,
			};
			callConnectedFn(obj);
		}

		// 发送ice-candidate
		if (Content.type == "ice-candidate") {
			console.log('Vue发送ice-candidate')
			let obj: any = {
				cmd: "webrtc",
				user_id: friendInfo.value.id,
				type: "ice-candidate",
				candidate: Content.candidate,
			};
			iceCandidateArr.push(obj);
			handleICECandidateFn(iceCandidateArr);

		}
	}
});

onUnload(() => {
	instance?.stopVoice();
	/*#ifdef H5*/
	window.removeEventListener("message", message, false);
	/*#endif*/

});

let url = "/static/ts/webrtc/";

let WebRtcConfig = uni.getStorageSync("WebRtcConfig");


// 等待对方接受邀请
const callDataFn = (obj: any) => {
	let callData = encodeURIComponent(JSON.stringify(obj));
	webSrc.value = `${url}webrtc.html?callData=${callData}&WebRtcConfig=${encodeURIComponent(JSON.stringify(WebRtcConfig))}&v=${new Date().getTime()}`;
	console.log('Vue等待对方接受邀请Fn----', new Date().getTime())
};
// 邀请你接受语音通话
const formCallDataFn = (obj: any) => {
	let formCallData = encodeURIComponent(JSON.stringify(obj));
	webSrc.value = `${url}webrtc.html?formCallData=${formCallData}&WebRtcConfig=${encodeURIComponent(JSON.stringify(WebRtcConfig))}&v=${new Date().getTime()}`;
	console.log('Vue邀请你接受语音通话Fn----', new Date().getTime())
};

// 接受对方的call
const callOfferFn = (obj: any) => {
	console.log('Vue接受对方的call----1', new Date().getTime())
	let callOffer = JSON.stringify({ ...obj, time: new Date().getTime() });

	const chunkSize = Math.ceil(callOffer.length / 5);
	let offerUrls = []; // 用于存储生成的 URL

	// 每 500ms 执行一次
	let index = 0;
	const intervalId = setInterval(() => {
		if (index < 5) {
			let chunk = callOffer.slice(index * chunkSize, (index + 1) * chunkSize);
			let encodedChunk = encodeURIComponent(chunk); // 对每个部分进行编码
			console.log(`offer${index}:`, encodedChunk);

			offerUrls.push(`${url}offer.html?offer${index}=${encodedChunk}`);

			// 赋值到对应的 offer
			offer0.value = offerUrls[index];
			index++;
		} else {
			clearInterval(intervalId); 
		}
	}, 300);

};

// 已接通电话
const callConnectedFn = (obj: any) => {
	let callConnected = encodeURIComponent(
		JSON.stringify({ ...obj, time: new Date().getTime() })
	);
	webSrc2.value = `${url}webrtc2.html?callConnected=${callConnected}&v=${new Date().getTime()}`
	console.log('Vue已接通电话Fn----', new Date().getTime())
};
// 发送handleICECandidate
const handleICECandidateFn = (iceCandidateArr: any) => {
	let handleICECandidate = encodeURIComponent(
		JSON.stringify({ iceCandidateArr, time: new Date().getTime() })
	);
	webSrc2.value = `${url}webrtc2.html?handleICECandidate=${handleICECandidate}&v=` + new Date().getTime();
	console.log('VuehandleICECandidateFn----', new Date().getTime())
};
// 自定义数据
const customMessageFn = (obj: any) => {
	console.log(obj, "Vue自定义数据");
	let customMessage = encodeURIComponent(
		JSON.stringify({ ...obj, time: new Date().getTime() })
	);
	webSrc2.value = `${url}webrtc2.html?customMessage=${customMessage}&v=` + new Date().getTime();
	console.log('VuecustomMessageFn----', new Date().getTime())
};

const message = async (e: any) => {
	let data: any = {};

	// 区分平台获取消息数据
	/*#ifdef H5*/
	data = e.data;
	/*#endif*/

	/*#ifdef APP-PLUS*/
	data = e.detail.data[0];
	/*#endif*/
	if (!data.type) {
		return;
	}

	console.log("Vuemessage---", data);

	// 根据消息类型处理逻辑
	switch (data.type) {
		case "offer":
		case "ice-candidate": {
			// 处理通话相关消息
			sendMessageFn(data);
			break;
		}
		case "answer": {
			isCallStatus = 1;
			// 处理通话相关消息
			sendMessageFn(data);
			break;
		}

		case "goBack": {
			if (goBack) {
				goBack = false;
				instance?.stopVoice();

				let content: any = { type: 2 };
				let Text = "";
				if (data.formattedTime) {
					console.log(`通话时长 ${data.formattedTime}`);
					content["formattedTime"] = data.formattedTime;
					Text = data.formattedTime;
				}

				uni.setStorageSync("submitSendRed", 1);

				let MessageId = Date.now();

				if (data.message_type === 8) {
					uni.showToast({ title: "对方无人接听", icon: "none" });
					let res = await noOneAnswered();
					MessageId = res.MessageId;
				} else {
					uni.showToast({ title: "通话已退出", icon: "none" });
				}

				saveDataChatList(Text, MessageId, data.clickType);
				const obj = {
					type: "push",
					content: JSON.stringify(content),
				};

				console.log("Text----", Text);
				sendMessageFn(obj);
				await MessageReadReceipt({
					key: friendInfo.value.SessionId,
				});

				setTimeout(
					() => {
						instance?.goBack(1);
					},
					data.clickType ? 1000 : 100
				);
			}
			break;
		}

		case "connected": {
			// 通话已接通
			instance?.stopVoice();
			uni.showToast({ title: "通话已接通", icon: "none" });
			sendMessageFn(data);
			break;
		}

		case "push": {
			// 自定义消息推送
			webviewShow.value = false
			uni.hideLoading()
			console.log("自定义消息推送", data);
			sendMessageFn(data);
			break;
		}
		case "interfaceLoaded": {
			// 界面加载完成
			instance?.playVoice(1);
			break;
		}
		default: {
			console.warn("未知的消息类型", data.type);
			break;
		}
	}
};

// 无人接听
const noOneAnswered = async () => {
	let obj: any = {
		message_type: 8,
		user_id: Number(friendInfo.value.id),
		message_content: {
			call_type: chatInfo.value.call_type,
		},
	};
	let res = await PersonalSend(obj);
	return res;
};

// 已取消保存本地数据库
const saveDataChatList = async (
	Text: string,
	MessageId: number,
	clickType: number
) => {
	let myUserInfo = uni.getStorageSync("userInfo");
	let obj = {
		myUserId: myUserInfo.user_id,
		Sender: clickType ? myUserInfo.user_id : Number(friendInfo.value.id),
		chatId: Number(friendInfo.value.id),
		MessageId,
		Cmd: 7,
		Time: Date.now(),
		id: friendInfo.value.id + "_" + MessageId,
		Grade: 1,
		unread: 0,
		UserId: Number(friendInfo.value.id),
		Type: 1,
		Content: {
			Text,
			isCallStatus,
			call_type: chatInfo.value.call_type,
		},
	};

	await instance?.$db.saveData("singleChat", [obj]);

	await setChatList(
		{
			Cmd: 7,
			Sender: Number(friendInfo.value.id),
			UserId: Number(friendInfo.value.id),
			Time: Date.now(),
			Type: 1,

			Content: {
				Text,
				call_type: chatInfo.value.call_type,
			},
		},
		Number(friendInfo.value.id)
	);
};

const sendMessageFn = (data: any, user_id = "") => {
	if (data.offer && isValidJson(data.offer)) {
		data.offer = JSON.parse(data.offer);
	}
	if (data.answer && isValidJson(data.answer)) {
		data.answer = JSON.parse(data.answer);
	}

	if (data.candidate && isValidJson(data.candidate)) {
		data.candidate = JSON.parse(data.candidate);
	}
	if (data.content && isValidJson(data.content)) {
		data.content = JSON.parse(data.content);
	}
	if (data.type == "push") {
		data = {
			cmd: "webrtc",
			user_id: user_id ? user_id : friendInfo.value.id,
			type: "push",
			content: data.content,
		};
	}

	console.log(data, "发送websocket数据", friendInfo.value.id);

	sendMessage(data);
};
const isValidJson = (str: any) => {
	try {
		JSON.parse(str);
		return true; // 如果解析成功，说明是有效的 JSON
	} catch (e) {
		return false; // 如果解析失败，说明不是有效的 JSON
	}
};

/*#ifdef H5*/
window.addEventListener("message", message, false);

// window.addEventListener("beforeunload", (event) => {
//   instance?.goBack(1);
// });
/*#endif*/
</script>
<style>
.bgMask {
	overflow: hidden;
	height: 100%;
	width: 100%;

}

.hide {
	opacity: 0 !important;
}

.bgMaskImg {
	position: fixed;
	top: 0;
	left: 0;
	z-index: 1000;
	width: 100%;
	height: 100%;
}
</style>